﻿using System;
using System.Threading.Tasks;
using UnityEngine;
using System.Threading;

namespace TlsService
{
    public class ContinueRecord
    {
        public Tls tls { get; private set; }
        private AudioClip recordingClip;
        private bool bRecording;
        private const int rate = 16000;
        private const int recordSeconds = 10;
        private const int packetSize = 6400;
        private const int interval = 20;
        private int lastWritePos = 0;
        
        

        public ContinueRecord()
        {
            tls = new Tls();
        }

        public async void StartRecord()
        {   
            if(Microphone.IsRecording(null)) 
                return;
            if (Microphone.devices.Length <= 0) return;
            bRecording = true;
            lastWritePos = 0;
            tls.Open();
            Recording();
       
        }

        public async void StopRecord()
        {
            if (bRecording == false)
                return;
            Microphone.End(null);
            tls.SendEndStream();
        }
        private async Task Recording()
        {
            recordingClip = Microphone.Start(null, true, recordSeconds, rate);
            while (!(Microphone.GetPosition(null) > 0))
            {
                await Task.Yield();
            }

            int position = Microphone.GetPosition(null);
            float[] audioData = null;
            int length = 0;
            while (bRecording)
            {
                await Task.Delay(interval);
                position = Microphone.GetPosition(null);
                audioData = null;
                if (position > lastWritePos)
                {
                    audioData = new float[packetSize];
                    length = position - lastWritePos;
                    if (length > audioData.Length) length = audioData.Length;
                    recordingClip.GetData(audioData, lastWritePos);
                    lastWritePos = position;
                }
                else if(position<lastWritePos)
                {
                    lastWritePos = 0;
                }

                if (audioData != null)
                {
                    byte[] byteData = ConvertFloatArrayToByteArray(audioData, length);
                    tls.SendAudioStream(byteData);
                }
            }
        }

        private byte[] ConvertFloatArrayToByteArray(float[] floatArray, int length)
        {
            byte[] byteArray = new byte[length * 2];
            for (int i = 0; i < length; i++)
            {
                short shortValue = (short)(floatArray[i] * 32767);
                byte[] bytes = System.BitConverter.GetBytes(shortValue);
                Array.Copy(bytes, 0, byteArray, i * 2, 2);
            }
            return byteArray;
        }
    }
}